﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
using System.Text;

using System.Net;
using BartonExtension;

using Model.Weixin;
using Model.App;
using Model.Images;
using Cache.Model;
using Cache.Utils;
using Cache;

using Senparc.Weixin.MP.Entities.Request;
using Senparc.Weixin.MP.MessageHandlers;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.Helpers;
using Senparc.Weixin.MP.MvcExtension;
using Senparc.Weixin.Exceptions;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin;

namespace iShangMai.Models
{
    public class WeixinImage
    {
        public string localPath { get; set; }
        public string mediaId { get; set; }
    }
    public class WeixinImageHelper
    {
        public static Task<List<WeixinImage>> DownloadImageWithMediaId(string mediaids)
        {
            return Task.Factory.StartNew<List<WeixinImage>>(() =>
                {
                    List<WeixinImage> imglist = new System.Collections.Generic.List<WeixinImage>();
                    string tmpPath = HttpContext.Current.Server.MapPath("~/userdata/tmp");
                    if (!Directory.Exists(tmpPath))
                    {
                        Directory.CreateDirectory(tmpPath);
                    }

                    if (!JSSDKAccess.loaded)
                    {
                        JSSDKAccess.Init();
                    }
                    mediaids.Split(';').ToList().ForEach(id =>
                        {
                            string url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}".FormatWith(JSSDKAccess.acs_token, id);
                            string response = string.Empty;
                            try
                            {
                                Encoding encoding = Encoding.GetEncoding("utf-8");
                                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
                                httpRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
                                httpRequest.ContentType = "application/json";
                                httpRequest.Method = "GET";
                                WebResponse resp = httpRequest.GetResponse();
                                if(resp.ContentType == "image/jpeg")
                                {
                                    string localPath = tmpPath + "\\" + DateTime.Now.DateTimeFileName() + ".jpg";
                                    Stream imageStream = resp.GetResponseStream();
                                    byte[] buffer = new byte[imageStream.Length];
                                    imageStream.Read(buffer, 0, buffer.Length);
                                    using (FileStream fs = new FileStream(localPath, FileMode.Create))
                                    {
                                        fs.Write(buffer, 0, buffer.Length);
                                    }
                                    WeixinImage wi = new WeixinImage()
                                    {
                                        localPath = localPath,
                                        mediaId = id
                                    };
                                    imglist.Add(wi);
                                }
                                else
                                {
                                    Dictionary<string, object> respJson = new System.Collections.Generic.Dictionary<string, object>();
                                    Stream st = resp.GetResponseStream();
                                    using (StreamReader sr = new StreamReader(st, encoding))
                                    {
                                        respJson = sr.ReadToEnd().FromJson<Dictionary<string, object>>();
                                    }
                                    if(respJson.ContainsKey("errorcode"))
                                    {
                                        //log it
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                //log it
                            }
                        });
                    return imglist;
                });
        }
    }
}